<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

class RechargeLog extends Model
{
    // 表名
    protected $name = 'recharge_log';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'create_time_text',
        'pay_time_text',
        'status_text',
	    'type_text',
	    'pay_type_text',
    ];
    

    
    public function getStatusList()
    {
        return self::$_status;
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['pay_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }
	
	public function getTypeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['type'];
		$list = FundsRecord::$_account_type;
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	public function getPayTypeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['pay_type'];
		$list = self::$_pay_type;
		return isset($list[$value]) ? $list[$value] : '';
	}
	
    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
	
	const TYPE_1 = 1;
	const TYPE_2 = 2;
	const TYPE_3 = 3;
	const TYPE_4 = 4;
	const TYPE_5 = 5;
	const TYPE_6 = 6;
	
	
	const STATUS_W = 0;
	const STATUS_Y = 1;
	const STATUS_C = 2;
	
	/**
	 * @var array 充值类型
	 */
	public static $_type = [
		self::TYPE_1 => '余额',
		self::TYPE_2 => '积分',
		self::TYPE_3 => '话费',
		self::TYPE_4 => '优惠券',
	];
	
	/**
	 * @var array 支付方式
	 */
	public static $_pay_type = [
		self::TYPE_1 => '余额',
		self::TYPE_2 => '积分',
		self::TYPE_3 => '话费',
		self::TYPE_4 => '优惠券',
		self::TYPE_5 => '支付宝',
		self::TYPE_6 => '微信',
	];
	
	/**
	 * 订单状态
	 */
	public static $_status = [
		self::STATUS_W => '待支付',
		self::STATUS_Y => '充值成功',
		self::STATUS_C => '取消充值'
	];
	
	
	public function user(){
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	
	/**
	 * 在线充值验证通过后的操作
	 * @param $pay_no 充值订单号
	 * @param $amount 充值金额
	 * @param $trade_no 第三方流水号
	 * @param $payType 支付方式
	 * @return bool|void
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function paySuccess($pay_no, $amount, $trade_no, $payType){
		$batch = Db::name('rechargeLog')->where('order_no',$pay_no)->find();
		if (!$batch) {
			$this->error = '订单不存在';return;
		}
		
		if ($batch['status'] != RechargeLog::STATUS_W) {
			$this->error = '非待支付订单';return;
		}
		
		if($batch['pay_amount'] != $amount) {
			$this->error = '金额不正确';return;
		}
		
		
		$this->startTrans();
		try{
			
			$batchData = [
				'status' => self::STATUS_Y,
				'pay_time' => time(),
				'out_trade_no' => $trade_no,
				'pay_type' => $payType
			];
			$batchReault = Db::name('rechargeLog')->where('id',$batch['id'])->update($batchData);
			if (!$batchReault) {
				throw new Exception('更改支付状态出错');
			};
			
			//充值对应的金额
			$files = RechargePackage::$_fields;
			
			//支付的用户
			$user = Db::name('user')->where(['id' => $batch['recharge_user_id']])->find();
			$field = $files[$batch['type']];
			$userData[$field] = $user[$field] + $batch['amount'];
			
			//如果充值类型为话费，添加对应有效期
			if($batch['type'] == self::TYPE_3){
				$time = time();
				if($user['phone_time']>$time){
					$time = $user['phone_time'];
				}
				
				$userData['phone_time'] = $time+$batch['days']*24*3600;
			}
			
			$logModel = new FundsRecord();
			
			//套餐有赠送积分
			if($batch['gift_integral'] > 0) {
				if($field == 'integral') {
					$userData['integral'] = $userData['integral'] + $batch['gift_integral'];
				} else {
					$userData['integral'] = $user['integral'] + $batch['gift_integral'];
				}
				$logRes = $logModel->addRecord( $batch['recharge_user_id'], $batch['gift_integral'], $userData['integral'],FundsRecord::ACCOUNT_TYPE_INTEGRAL,$logModel::OPE_TYPE_PLUS, $logModel::TYPE_RECHARGE,'','充值套餐赠送');
				if(!$logRes){
					throw new Exception($logModel->getError());
				}
			}
			
			//套餐有赠送优惠券
			if($batch['gift_voucher'] > 0) {
				if($field == 'voucher_balance') {
					$userData['voucher_balance'] = $userData['voucher_balance'] + $batch['gift_voucher'];
				} else {
					$userData['voucher_balance'] = $user['voucher_balance'] + $batch['gift_voucher'];
				}
				$logRes = $logModel->addRecord($batch['recharge_user_id'], $batch['gift_integral'], $userData['voucher_balance'], FundsRecord::ACCOUNT_TYPE_VOUCHER,$logModel::OPE_TYPE_PLUS, $logModel::TYPE_RECHARGE,'','充值赠送');
				if(!$logRes){
					throw new Exception($logModel->getError());
				}
			}
			
			$res = Db::name('user')->where(['id' => $batch['recharge_user_id']])->update($userData);
			if(!$res){
				throw new Exception('添加用户'.RechargePackage::$_type[$batch['type']].'出错');
			}
			
			//添加增加的帐户流水记录
			$logRes = $logModel->addRecord($batch['recharge_user_id'], $batch['amount'], $user[$field],$batch['type'],$logModel::OPE_TYPE_PLUS, $logModel::TYPE_RECHARGE,'',self::$_pay_type[$payType].'充值'.RechargePackage::$_type[$batch['type']]);
			if(!$logRes){
				throw new Exception($logModel->getError());
			}
			
			//上级返利
			$rebateModel = new SettingRechargeRebate();
			$rebateRes = $rebateModel->rebate($user, $batch['pay_amount']);
			if(!$rebateRes) {
				throw new Exception('充值返利出错:'.$rebateModel->getError());
			}
			
			$this->commit();
			return true;
			
		} catch (Exception $e) {
			$this->error = $e->getMessage();
			return false;
		}
	}
}
